#pragma once
#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
 #include <fcntl.h>
 #include <sys/stat.h>
 #include <stdio.h>
 #include "comm.hpp"

using namespace std;

#define FIFO_FILE "fifo"

class NamedPipe
{
public:
    NamedPipe(const string& path, const string& name)
        :_path(path), _name(name)
    {
        _fifo_name = _path + "/" + _name;
        umask(0);
        int n = mkfifo(_fifo_name.c_str(), 0666);
        if(n < 0) 
        {
            ERR_EXIT("mkfifo");
        }
        cout << "fifo创建成功" << endl;
    }

    ~NamedPipe()
    {
        int n = unlink(_fifo_name.c_str());
        if(n < 0) 
        {
            ERR_EXIT("unlink");
        }
        cout << "fifo删除成功" << endl;
    }
private:
   string _path;
   string _name;
   string _fifo_name;
};

class FileOper
{
public:
    FileOper(const string& path, const string& name)
        :_path(path), _name(name), _fd(-1)
    {
        _fifo_name = _path + "/" + _name;
    }

    void OpenForRead()
    {
        _fd = open(_fifo_name.c_str(), O_RDONLY);
        if(_fd < 0) 
        {
            ERR_EXIT("open");
        }
        cout << "fifo打开成功" << endl;
    }

    bool Read()
    {
        char c;
        int n = read(_fd, &c, 1); //只要读一个字节就行
        if(n > 0) return true; 
        else return false;
    }

    void OpenForWrite()
    {
        _fd = open(_fifo_name.c_str(), O_WRONLY); //写方式打开
        if(_fd < 0)
        {
            ERR_EXIT("open");
        }
        cout << "client打开fifo成功" << endl;
    }

    void Write()
    {
        char c = 'a'; //这个字符是什么不重要，只要是一个字符就行
        int n = write(_fd, &c, 1);
    }

    void Close()
    {
        if(_fd > 0) close(_fd);
    }

    ~FileOper()
    {}
private:
   string _path;
   string _name;
   string _fifo_name;
   int _fd;
};

